import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';
import moment from 'moment';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { addTab, timeLimit } from '@/utils/utils';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Table,
  Button,
  Card,
  Col,
  Divider,
  Input,
  Row,
  Select,
  DatePicker,
  Tooltip,
  message,
  Popconfirm,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

import PrintView from './components/PrintView';

const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { pathname } = window.location;

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  logisCenterWithdrawList: any;
  INITINFO: any;
  checkPerm: any;
  currentUser: any;
  loading: boolean;
  screen: string;
}

interface TableListState {
  current: number;
  pageSize: number | undefined;
  formValues: any;
  backVisible: boolean;
  rowId:number;
}

/* eslint react/no-multi-comp:0 */
@connect(({
  logisCenterWithdrawList,
  common: { INITINFO, checkPerm },
  user: { currentUser },
  global: { screen },
  loading,
}: any) => ({
  logisCenterWithdrawList,
  INITINFO,
  checkPerm,
  currentUser,
  screen,
  loading: loading.effects['logisCenterWithdrawList/fetch'],
}))

class TableList extends React.Component<TableListProps, TableListState> {
  columns: any = [
    {
      title: '物流中心',
      dataIndex: 'logisName',
      width: 140,
      render: (text: string, record: any) => (
        <Tooltip title={text}>
          <div
            className="wordOmit namelink"
            onClick={() => this.handleShowWithdraw(record.expCode, record.orderId)}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '运单号',
      dataIndex: 'expCode',
      width: 120,
      render: (text: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '快递公司',
      dataIndex: 'expressName',
      width: 100,
      render: (text: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">
            {text || '--'}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '入库时间',
      dataIndex: 'inTime',
      width: 160,
      render: (text: string) => text || '--',
    },
    {
      title: '退回时间',
      dataIndex: 'finishedTime',
      width: 160,
    },
    {
      title: '退回原因',
      dataIndex: 'reason',
      width: 80,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '操作',
      width: 120,
      dataIndex: 'orderId',
      fixed: 'right',
      render: (orderId: any, record: any) => (
        <>
          <div>
            <Popconfirm
              title="确定取消退回当前订单？"
              onConfirm={() => this.handleChangeBackModal(orderId)}
              okText="确定"
              cancelText="取消"
            >
              <span style={{ color: '#1890FF', cursor: 'pointer' }}>取消退回</span>
            </Popconfirm>
            <Divider type="vertical" />
            <span
              className="operLink"
              onClick={() => this.handleShowWithdraw(record.expCode, orderId)}
            >
              详情
            </span>
          </div>
        </>
      ),
    },
  ];

  state: TableListState = {
    current: 1,
    pageSize: 20,
    formValues: {},
    backVisible: false,
    rowId: 0,
  };

  static getDerivedStateFromProps(props: any, state: any) {
    const { search } = props.location;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { page, psize, ...formValues } = query;

    return {
      ...state,
      formValues,
      current: Number(page) || 1,
      pageSize: Number(psize) || 20,
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    const { logisCenterWithdrawList: { data } } = this.props;

    if (data?.list?.length) return;

    this.fetchLogisList();
    this.fetchExpressList();
    this.fetchBackOrderList();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { formValues, current, pageSize } = this.state;

    if (!_.isEqual(formValues, prevState.formValues)
      || current !== prevState.current
      || pageSize !== prevState.pageSize) {
      this.setFieldsValue();
      this.fetchBackOrderList();
    }
  }

  // 设置表单值
  setFieldsValue = () => {
    const {
      formValues: { startTime, endTime, ...others },
    } = this.state;

    if (startTime) {
      others.start_end_day = [moment(startTime), moment(endTime)];
    } else {
      others.start_end_day = [
        moment(moment().subtract(7, 'days').format('YYYY-MM-DD 00:00:00')),
      ];
    }
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(others);
  }

  // 获取物流中心列表
  fetchLogisList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchLogisList',
    });
  }

  // 获取快递公司列表
  fetchExpressList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchExpressList2',
    });
  }

  // 获取数据
  fetchBackOrderList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterWithdrawList/fetch',
      payload: this.getQueryParams(),
    });
  }

  // 获取查询参数
  getQueryParams = () => {
    const {
      formValues,
      current: pageIndex,
      pageSize,
    } = this.state;
    const { logisId = {}, expressId = {} } = formValues;

    const params = {
      ...formValues,
      pageIndex,
      pageSize,
      logisId: logisId.key,
      expressId: expressId.key,
    };
    params.startTime = params.startTime || moment().subtract(7, 'days').format('YYYY-MM-DD 00:00:00');

    return params;
  };

  /**
   * 查询
   */
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((err, fieldsValue) => {
      if (err) return;

      const { start_end_day } = fieldsValue;
      fieldsValue.startTime = start_end_day[0]
        ? moment(fieldsValue.start_end_day[0]).format('YYYY-MM-DD HH:mm:ss')
        : moment().subtract(7, 'days').format('YYYY-MM-DD 00:00:00');

      fieldsValue.endTime = start_end_day[1]
        && moment(fieldsValue.start_end_day[1]).format('YYYY-MM-DD HH:mm:ss');
      delete fieldsValue.start_end_day;

      const query = { page: 1, ...fieldsValue };
      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '退回管理',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  /**
   * 重置
   */
  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '退回管理',
      url: pathname,
      isTopMenu: true,
    });
  };

  handleChangeBackModal = (orderId: number = 0) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterWithdrawList/cancel',
      payload: {
        search: this.getQueryParams(),
        orderId,
      },
    });
  }

  /** 打印交接单 */
  handlePirntReceipt = () => {
    const {
      form: { getFieldValue },
      logisCenterWithdrawList: { data = [] },
    } = this.props;
    const logis = getFieldValue('logisId') || {};
    const express = getFieldValue('expressId') || {};
    const start_end_day = getFieldValue('start_end_day') || [];

    if (!logis.key || !express.key || data.length > 1) {
      message.error('请选择物流中心和快递公司！');
    } else {
      const params = {
        logisId: logis.key,
        logisName: logis.label,
        expressId: express.key,
        expressName: express.label,
        startTime: start_end_day[0] && moment(start_end_day[0]).format('YYYY-MM-DD HH:mm:ss'),
        endTime: start_end_day[1] && moment(start_end_day[1]).format('YYYY-MM-DD HH:mm:ss'),
      };

      const { dispatch } = this.props;
      dispatch({
        type: 'logisCenterWithdrawList/fetchReceipt',
        payload: params,
      });
    }
  }

  /**
   * 取消退回
   */
  handleCancelWithdraw = (id: number, orderType: number, openCell: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterWithdrawList/cancel',
      payload: {
        query: this.getQueryParams(),
        params: { id, orderType, openCell },
      },
    });
  };

  /**
   * 查看详情
   */
  handleShowWithdraw = (expCode: string, orderId: number) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${expCode}`,
      url: `/logisCenter/withdraw/list/detail/${orderId}`,
    });
  };

  // 分页
  onSelectChange = (page: number, psize: number | undefined) => {
    const { formValues } = this.state;
    const query = { ...formValues, page, psize };
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '退回管理',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  onClickRow = ({ orderId }: any) => ({
    onClick: () => {
      this.setState({ rowId: orderId });
    },
  })

  setRowClassName = ({ orderId }: any) => {
    const { rowId } = this.state;
    return orderId === rowId ? 'clickRowStyl' : '';
  }

  // 渲染查询表单
  renderSearchFormElem = () => {
    const {
      form: { getFieldDecorator },
      INITINFO: { expressList, logisList },
    } = this.props;

    return (
      <Form onSubmit={this.handleSearch} className="tableListForm">
        <Row gutter={12}>
          <Col md={12} sm={24}>
            <FormItem label="起止时间" colon={false}>
              {getFieldDecorator('start_end_day')(
                <RangePicker
                  showTime
                  placeholder={['开始时间', '截止时间']}
                  style={{ width: '100%' }}
                  format="YYYY/MM/DD HH:mm:ss"
                  disabledDate={timeLimit}
                  ranges={{
                    今天: [moment().startOf('day'), moment().endOf('day')],
                    本周: [moment().startOf('week'), moment().endOf('week')],
                    本月: [moment().startOf('month'), moment().endOf('month')],
                    上月: [
                      moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                      moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                    ],
                  }}
                />,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="操作人手机" colon={false}>
              {getFieldDecorator('operPhone')(
                <Input allowClear type="text" placeholder="请输入" />,
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col md={6} sm={24}>
            <FormItem label="物流中心" colon={false}>
              {getFieldDecorator('logisId')(
                <Select
                  showSearch
                  allowClear
                  labelInValue
                  placeholder="请选择"
                  filterOption={(input: any, option: any) => (
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  )}
                >
                  {logisList.map((item: any) => (
                    <Option value={String(item.id)} key={item.id}>{item.name}</Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="　　运单号" colon={false}>
              {getFieldDecorator('expCode')(<Input allowClear placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="　快递公司" colon={false}>
              {getFieldDecorator('expressId')(
                <Select
                  showSearch
                  allowClear
                  labelInValue
                  placeholder="请选择"
                  filterOption={(input: any, option: any) => (
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  )}
                >
                  {expressList.map((express: any) => (
                    <Option value={String(express.id)} key={express.id}>{express.name}</Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <div className="flexFeView">
              <Button
                type="primary"
                htmlType="submit"
                className="smallButton"
              >
                查询
              </Button>
              <Button
                type="primary"
                className="addButton smallButton marginL16"
                onClick={this.handleReset}
              >
                重置
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const { current, pageSize } = this.state;
    const { logisCenterWithdrawList: { data }, screen, loading } = this.props;

    const pagination = data
      ? {
        total: data ? data.count : 0,
        pageSize,
        current: current || 1,
        onChange: this.onSelectChange,
        showTotal: () => `共${data.count || 0}条数据`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    if (screen === 'sm' || screen === 'lg') {
      delete this.columns[this.columns.length - 1].fixed;
    } else if (screen === 'md') {
      this.columns[this.columns.length - 1].fixed = 'right';
    }

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          {this.renderSearchFormElem()}
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="marginR16"
              onClick={() => this.handlePirntReceipt()}
            >
              打印交接单
            </Button>
          </div>
          <Table
            rowKey="expCode"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={data.list || []}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1200 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <PrintView />
      </>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
